<!--
 * @name order
 * @description 盛装舞步
 * @author idouya
 * @email elegentfrog@163.com
 * @date 2025-07-02
 -->

<template>
  <div class="p-order common-bg common-layout">
    <page-title
      :discipline="gameInfo.discipline"
      :event="gameInfo.event"
      :match="gameInfo.match"
      :type="gameInfo.type"
      :startTime="gameInfo.startTime"
      :eventName="gameInfo.eventName"
    ></page-title>
    <div class="content">
      <div class="title">
        <div class="order">序号</div>
        <div class="content-detail">
          <div class="horseOrder1">马号</div>
          <div class="delegation">单位</div>
          <div class="name">姓名</div>
          <div class="horseName">马名</div>
          <div class="appearTime">验马结果</div>
        </div>
      </div>
      <div class="info">
        <div class="item" v-for="(item, index) in showList" :key="index">
          <div class="order">{{ item.Order }}</div>
          <div class="item-wrap">
            <div class="item-detail">
              <div class="horseOrder1">{{ item.HorseBib }}</div>
              <div class="delegation">{{ item.CountryName }}</div>
              <div class="name">{{ item.AthleteName }}</div>
              <div :class="['horseName', item.HorseName.length > 15 ? 'horseNameAdapt' : '']">
                {{ item.HorseName }}
              </div>
              <div class="appearTime" :class="textColor(item.InspAnswer)">
                {{ item.InspAnswer }}
              </div>
            </div>
            <img src="@/assets/img/scb/line-divide.png" alt="" height="5px" width="100%" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import useStore from '@/store'
import Storage from '@/assets/js/storage'
import Utils from '@/assets/js/utils'
import Config from '@/assets/js/config'
import { useMultiProcRequest } from '@/assets/js/useMultiProcRequest'

const { results, fetchForProcs } = useMultiProcRequest()

const gameInfo = ref({
  discipline: '马术',
  match: '',
  event: 'DRESTEAM',
  type: '验马结果',
  startTime: '13:01:29',
  eventName: '',
})

const dataList = ref([])
const showList = ref([])
const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
const commonStore = useStore.useCommonStore()

const params = ref({})
const procName = ref([])
const page = ref(0)
const timer = ref(null)

// onUnmounted(() => {
//   clearInterval(timer.value)
// })
// onBeforeUnmount(() => {
//   clearInterval(timer.value)
// })

/** ✅ 页面挂载逻辑 **/
onMounted(async () => {
  // clearInterval(timer.value)
  showList.value = []
  dataList.value = []

  const currentMatchId = route.query.MatchID
  const lastMatchId = localStorage.getItem('lastMatchId')
  const lastPage = localStorage.getItem('lastPage')

  params.value = route.query
  procName.value = Config.procNameList[route.name]

  await getData()

  // ✅ 判断是否需要重置页码
  if (!lastMatchId || lastMatchId !== currentMatchId) {
    page.value = 0
  } else {
    page.value = lastPage ? Number(lastPage) : 0
  }

  getShowList()

  // ✅ 记录当前 MatchID
  localStorage.setItem('lastMatchId', currentMatchId)
})

/** ✅ 文字颜色渲染逻辑 **/
const textColor = (text) => {
  switch (text) {
    case '通过':
      return 'pass'
    case '未通过':
      return 'failed'
    case '待检':
      return 'await'
    case '复检':
      return 'retest'
    default:
      return ''
  }
}

/** ✅ 获取数据 **/
const getData = async () => {
  if (procName.value.length > 0) {
    await fetchForProcs(procName.value, {
      procName: procName.value[0],
      keyValues: params.value,
    })
  }
}

/** ✅ 分页逻辑 **/
const getShowList = () => {
  if (timer.value) clearInterval(timer.value)
  if (!dataList.value.length) return

  const pageSize = 8
  const maxPage = Math.ceil(dataList.value.length / pageSize) - 1

  // ✅ 先立即展示当前页（或第一页）
  showList.value = dataList.value.slice(page.value * pageSize, (page.value + 1) * pageSize)
  localStorage.setItem('lastPage', page.value)
}

/** ✅ 数据监听 **/
watchEffect(() => {
  if (results.value?.datasetList) {
    gameInfo.value.event = results.value.datasetList[0][0]?.EventCode
    gameInfo.value.match = results.value.datasetList[0][0].MatchName
    gameInfo.value.eventName = results.value.datasetList[0][0].EventName
    dataList.value = results.value.datasetList[1]
    getShowList()
  }
})

/** ✅ 接收到新消息时刷新 **/
watch(
  () => commonStore.receivedActionMessages,
  async (newVal) => {
    if (newVal.length > 0) {
      const latestMsg = newVal[newVal.length - 1]
      const data = latestMsg?.data
      page.value = data?.pageIndex || 0
    }
  },
  { deep: true }
)

/** ✅ 监听路由变化（MatchID切换时重置） **/
watch(
  () => route.query,
  async (val) => {
    // clearInterval(timer.value)
    showList.value = []
    dataList.value = []
    params.value = val

    const currentMatchId = val.MatchID
    const lastMatchId = localStorage.getItem('lastMatchId')

    await getData()

    if (!lastMatchId || lastMatchId !== currentMatchId) {
      page.value = 0 // MatchID变化 → 回第一页
    }

    getShowList()
    localStorage.setItem('lastMatchId', currentMatchId)
  }
)
</script>

<style scoped lang="scss">
@import '@/assets/scss/scb/orderDressage';

.horseOrder1 {
  width: 7%;
  text-align: center;
}

.delegation {
  width: 12%;
}

.retest {
  color: #ffa500;
}

.pass {
  color: #7fff00;
}

.failed {
  color: #ff0000;
}

.await {
  color: #ffffff;
}
</style>
